package com.heima.wemedia.controller.v1;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.model.common.dtos.common.PageDto;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.service.WmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/v1/sensitive")
public class WmSensitiveController {
    @Autowired
    private WmSensitiveService wmSensitiveService;

    /**
     * 分页查询敏感词列表
     * @param pageDto
     * @return
     */
    @PostMapping("/list")
    public ResponseResult list(@RequestBody PageDto pageDto) {
        return wmSensitiveService.pageList(pageDto);
    }

    /**
     * 不分页查询所有违禁词信息
     * @return
     */
    @GetMapping("/sensitives")
    public ResponseResult getSensitives() {
        List<WmSensitive> list = wmSensitiveService.list();
        return ResponseResult.okResult(JSON.toJSONString(list));
    }
    @PostMapping("/save")
    public ResponseResult save(@RequestBody WmSensitive wmSensitive) {
        //检验参数
        if(wmSensitive.getSensitives()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询敏感词表中是否有新增的敏感词，若有则不添加，没有则添加
        LambdaQueryWrapper<WmSensitive> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmSensitive::getSensitives, wmSensitive.getSensitives());
        WmSensitive wmSensitiveOne = wmSensitiveService.getOne(wrapper);
        if(wmSensitiveOne!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"该敏感词已存在");
        }
        wmSensitive.setCreatedTime(new Date());
        wmSensitiveService.save(wmSensitive);
        return ResponseResult.okResult(wmSensitive);
    }
    @PostMapping("/update")
    public ResponseResult update(@RequestBody WmSensitive wmSensitive) {
        LambdaUpdateWrapper<WmSensitive> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(WmSensitive::getId, wmSensitive.getId()).set(WmSensitive::getSensitives, wmSensitive.getSensitives());
        wmSensitiveService.update(wmSensitive, wrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @DeleteMapping("/del/{sensitiveId}")
    public ResponseResult del(@PathVariable("sensitiveId") Long sensitiveId) {
        wmSensitiveService.removeById(sensitiveId);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
